import React, { useState, useEffect } from 'react';
import { 
  Table, 
  Button, 
  Space, 
  Modal, 
  Form, 
  Input, 
  Select, 
  message,
  Tag,
  Popconfirm 
} from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import api from '../services/authService';

const { Option } = Select;

interface Application {
  id: number;
  name: string;
  description: string;
  app_type: string;
  repository_url: string;
  is_active: boolean;
  created_at: string;
}

const Applications: React.FC = () => {
  const [applications, setApplications] = useState<Application[]>([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingApp, setEditingApp] = useState<Application | null>(null);
  const [form] = Form.useForm();

  useEffect(() => {
    fetchApplications();
  }, []);

  const fetchApplications = async () => {
    setLoading(true);
    try {
      const response = await api.get('/applications/');
      setApplications(response.data);
    } catch (error) {
      message.error('获取应用列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleCreate = () => {
    setEditingApp(null);
    form.resetFields();
    setModalVisible(true);
  };

  const handleEdit = (app: Application) => {
    setEditingApp(app);
    form.setFieldsValue(app);
    setModalVisible(true);
  };

  const handleDelete = async (id: number) => {
    try {
      await api.delete(`/applications/${id}`);
      message.success('删除成功');
      fetchApplications();
    } catch (error) {
      message.error('删除失败');
    }
  };

  const handleSubmit = async (values: any) => {
    try {
      if (editingApp) {
        await api.put(`/applications/${editingApp.id}`, values);
        message.success('更新成功');
      } else {
        await api.post('/applications/', values);
        message.success('创建成功');
      }
      setModalVisible(false);
      fetchApplications();
    } catch (error) {
      message.error(editingApp ? '更新失败' : '创建失败');
    }
  };

  const columns = [
    {
      title: '应用名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
    },
    {
      title: '类型',
      dataIndex: 'app_type',
      key: 'app_type',
      render: (type: string) => (
        <Tag color={type === 'docker' ? 'blue' : type === 'k8s' ? 'green' : 'orange'}>
          {type.toUpperCase()}
        </Tag>
      ),
    },
    {
      title: '仓库地址',
      dataIndex: 'repository_url',
      key: 'repository_url',
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'is_active',
      key: 'is_active',
      render: (active: boolean) => (
        <Tag color={active ? 'green' : 'red'}>
          {active ? '活跃' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: Application) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />}
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除这个应用吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
        <h1>应用管理</h1>
        <Button type="primary" icon={<PlusOutlined />} onClick={handleCreate}>
          创建应用
        </Button>
      </div>

      <Table
        columns={columns}
        dataSource={applications}
        loading={loading}
        rowKey="id"
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条记录`,
        }}
      />

      <Modal
        title={editingApp ? '编辑应用' : '创建应用'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={() => form.submit()}
        width={600}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="应用名称"
            rules={[{ required: true, message: '请输入应用名称' }]}
          >
            <Input placeholder="请输入应用名称" />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <Input.TextArea placeholder="请输入应用描述" />
          </Form.Item>

          <Form.Item
            name="app_type"
            label="应用类型"
            rules={[{ required: true, message: '请选择应用类型' }]}
          >
            <Select placeholder="请选择应用类型">
              <Option value="docker">Docker</Option>
              <Option value="k8s">Kubernetes</Option>
              <Option value="static">静态文件</Option>
            </Select>
          </Form.Item>

          <Form.Item
            name="repository_url"
            label="仓库地址"
          >
            <Input placeholder="请输入仓库地址" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default Applications;
